<template>
  <div class="radar-box">
    <div v-if="showChart" ref="chart" style="width: 100%; height: 100%"></div>
    <nodata-box v-else></nodata-box>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { addZero } from '@/utils/util/format'

export default {
  name: 'RadarChart',
  props: {
    data: {
      // NOTE: undefined表示数据仍在加载中
      type: Array,
      default: undefined
    },
    indicator: {
      type: Array,
      default: () => []
    },
    colors: {
      type: Array,
      default: () => {
        return ['#4c87e8', '#3cca61']
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  computed: {
    showChart: function () {
      return this.data === undefined || this.data.length > 0
    },
    series: function () {
      return [
        {
          type: 'radar',
          data: this.data,
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 1
          },
          symbol: 'circle',
          symbolSize: 8
        }
      ]
    },
    radar: function () {
      return {
        indicator: this.indicator.map((x) => ({
          name: x.name,
          max: x.max || 60000
        })),
        center: ['35%', '50%'],
        radius: '70%',
        axisName: {
          color: '#595959'
        },
        axisLine: {
          lineStyle: {
            color: '#f0f0f0'
          }
        },
        splitLine: {
          lineStyle: {
            color: '#f0f0f0'
          }
        },
        splitArea: {
          areaStyle: {
            color: ['transparent', '#fafafa']
          }
        }
      }
    }
  },
  watch: {
    data() {
      this.updateChart()
    }
  },
  mounted() {
    this.initChart()
    this.updateChart()
    // 屏幕缩放的时候，重绘echart
    window.addEventListener('resize', this.resize, false)
  },
  unmounted() {
    this.destroyChart()
    window.removeEventListener('resize', this.resize, false)
  },
  methods: {
    initChart() {
      if (this.chart || !Array.isArray(this.data) || this.data.length === 0) {
        return
      }

      this.chart = echarts.init(this.$refs.chart)
      return
    },
    resize() {
      if (this.chart) {
        this.chart.resize()
      }
    },
    buildOption() {
      const { width } = this.$refs.chart.getBoundingClientRect()
      const indicator = this.indicator
      return {
        legend: {
          show: true,
          right: '10%',
          top: 'middle',
          height: 160,
          itemWidth: 0,
          itemHeight: 0,
          type: 'scroll',
          orient: 'vertical',
          selectedMode: false,
          pageIconSize: 10,
          formatter: (name) => {
            const itemIdx = this.data.findIndex((x) => x.name === name)
            const wordNum = Math.floor((width * 0.2) / 12) - 1
            let newName = name
            if (name.length > wordNum) {
              newName = name.substring(0, wordNum) + '...'
            }
            return '{rect|}{a|' + addZero(itemIdx + 1) + '. ' + newName + '}' // 使用 rect 标记 + 文本的方式来自定义 icon
          },
          // 自定义图例样式
          textStyle: {
            fontSize: 12,
            lineHeight: 18,
            fontWeight: 400,
            rich: {
              rect: {
                width: 12,
                height: 12,
                borderRadius: 2,
                backgroundColor: '{color| }'
              },
              a: {
                color: '#595959',
                padding: [0, 0, 0, 8],
                fontFamily: 'PingFangSC-Regular, PingFang SC'
              }
            }
          }
        },
        color: this.colors,
        grid: {
          containLabel: true
        },
        tooltip: {
          show: true,
          extraCssText:
            'box-shadow: 0px 2px 10px 0px rgba(0,0,0,0.16);border-radius: 2px;border: 1px solid #D9D9D9;padding: 8px;',
          formatter: function (params) {
            const { color, name, value } = params
            const valueHtml = value.map((val, index) => {
              return `<div class="series-item">
                <div class='marker' style="background-color:${color}"></div>
                <div class="content-name">${indicator[index].name}</div>
                <div class="content-value">${val}</div>
              </div>`
            })
            const legendHtml = `<div class="tooltip-container">
                <div class="name">${name}</div>
                <div class="content">${valueHtml.join('')}</div>
              </div>
            </div>`
            return legendHtml
          }
        },
        series: this.series,
        radar: this.radar
      }
    },
    destroyChart() {
      if (!this.chart) {
        return
      }

      this.chart.dispose()
      this.chart = null
    },
    updateChart() {
      if (!this.chart) {
        this.initChart()
      }

      if (this.chart) {
        this.chart.clear()
        const currentOptions = this.buildOption()
        this.chart.setOption(currentOptions)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.radar-box {
  position: relative;
  width: 100%;
  height: 100%;
}

::v-deep {
  .series-item {
    display: flex;
    align-items: center;
    width: 100%;

    .marker {
      flex: 0 0 auto;
      margin-right: 8px;
      width: 6px;
      height: 6px;
      border-radius: 6px;
    }

    .content-name {
      color: #5c5c5c;
      font-weight: 400;
      margin-right: 8px;
    }

    .content-value {
      flex: 1;
      width: 1%;
      text-align: right;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #262626;
      margin-left: 8px;
    }
  }
}
</style>
